package com.youpai.platform.chat.service.service.impl;

import com.youpai.platform.chat.service.entity.dto.SendSystemMessageDTO;
import com.youpai.platform.chat.service.entity.po.ChatMessagePO;
import com.youpai.platform.chat.service.mapper.ChatMessageMapper;
import com.youpai.platform.chat.service.service.SystemMessageService;
import com.youpai.platform.chat.service.util.ChatUtils;
import com.youpai.platform.common.util.id.IdGenerator;
import com.youpai.platform.vulture.common.enums.MsgTypeEnum;
import com.youpai.platform.vulture.common.enums.ServerCommandEnum;
import com.youpai.platform.vulture.service.entity.dto.SendMessageDTO;
import com.youpai.platform.vulture.service.router.MessageRouterService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @date: 2023/2/11
 * @author: Welles
 * @version: 1.0
 * @description: 系统消息服务
 */
@Component
public class SystemMessageServiceImpl implements SystemMessageService {

    @Resource
    private MessageRouterService messageRouterService;
    @Resource
    private ChatMessageMapper chatMessageMapper;

    @Override
    public void sendSystemMessage(SendSystemMessageDTO systemMessageDTO) {
        // 插入消息
        insertMessage(systemMessageDTO);
        SendMessageDTO sendMessageDTO = buildSendMessageDTO(systemMessageDTO);
        // 进行推送
        messageRouterService.sendMessage(sendMessageDTO);
    }

    private SendMessageDTO buildSendMessageDTO(SendSystemMessageDTO systemMessageDTO) {
        SendMessageDTO sendMessageDTO = new SendMessageDTO();
        sendMessageDTO.setCmd(ServerCommandEnum.SRV_PUSH_MSG.cmd)
                .setToAccId(systemMessageDTO.getUid())
                .setBody(systemMessageDTO.getContent());
        return sendMessageDTO;
    }

    private void insertMessage(SendSystemMessageDTO sendSystemMessageDTO) {
        ChatMessagePO chatMessagePO = new ChatMessagePO();
        Long msgId = IdGenerator.generateId();
        chatMessagePO.setMessageId(msgId)
                .setContent(sendSystemMessageDTO.getContent())
                .setMsgType(MsgTypeEnum.SYSTEM.type)
                .setSessionId(ChatUtils.buildSessionId(sendSystemMessageDTO.getSystemAccId(), sendSystemMessageDTO.getUid()))
                .setFromAccId(sendSystemMessageDTO.getSystemAccId())
                .setToAccId(sendSystemMessageDTO.getUid())
                .setTimeStamp(System.currentTimeMillis());
        chatMessageMapper.insertChatMessagePO(chatMessagePO);
    }


}
